package com.example.community.controller;

import com.example.community.entity.Event;
import com.example.community.entity.User;
import com.example.community.event.EventProducer;
import com.example.community.service.LikeService;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUitl;
import com.example.community.util.HostHolder;
import com.example.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *
     * @param entityType 实体类型
     * @param entityId 实体id
     * @param entityUserId 该实体作者的用户id
     * @param postId 帖子id
     * @return
     */
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId){
        User user = hostHolder.getUser();

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 数量
        long likeCount = likeService.findEntityLIkeCount(entityType, entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);


        // 触发点赞事件
        if(likeStatus == 1){
            Event event = new Event();
            event.setTopic(TOPIC_LIKE);     // 主题为点赞
            event.setUserId(hostHolder.getUser().getId());  //当前用户
            event.setEntityType(entityType);    // 实体类型 帖子、评论
            event.setEntityId(entityId);        // 实体id
            event.setEntityUserId(entityUserId);    // 发表该实体的用户id
            event.setData("postId", postId);    // 帖子id -- 要链接到被点赞的帖子

            eventProducer.fireEvent(event);
        }
        // 如果给帖子点赞
        if(entityType == ENTITY_TYPE_POST){
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);

        }

        return CommunityUitl.getJSONString(0, null, map);

    }


}
